package com.gopay.checkorder.service.task.batch;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.Resource;

import com.gopay.gass.service.GassPayRemoteService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.dao.BisBankOrderQueryDAO;
import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.BcdlOrderSendBankService;
import com.gopay.checkorder.service.sentinel.BcdlOrderSentinel;
import com.gopay.checkorder.service.task.Task;
import com.gopay.checkorder.service.task.thread.batch.BcdlResultDeal4BatchThread;
import com.gopay.common.constants.autosettle.SettlementExchangeConstants;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BankOrderType;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.manager.order.CpsGeneralMainOrderQueryManager;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.domain.bank.bcdl.BcdlPacketRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.HttpTransport;
import com.gopay.common.util.StringTools;
import com.gopay.common.util.spring.SpringContextUtil;

/**
 * 工行批量付款发起——一体机
 *
 * @author lynn
 * @data
 */
public class BcdlOrderBatchSendAIOTaskImpl implements Task{

	private final static Logger logger = LoggerFactory.getLogger(BcdlOrderBatchSendAIOTaskImpl.class);

	@Resource(name = "bankOrderService")
	private BankOrderService bankOrderService;
	private int MAX_SIZE = 300;

	@Resource(name = "cpsGeneralMainOrderQueryManager")
	protected CpsGeneralMainOrderQueryManager mainOrderQuery;
	@Resource(name = "bankOrderManager")
	protected BankOrderManager bankOrderManager;

	@Resource(name = "bisBankOrderQueryDAO")
	private BisBankOrderQueryDAO bisBankOrderQueryDAO;

	@Resource(name = "commonQueryDAO")
	private CommonQueryDAO commonQueryDAO;
	@Resource(name = "gassPayService")
	private GassPayRemoteService gassPayService;
	private String bank;
	private String label;
	private int remainder;
	private int modInt;
	private String across;
	private String packetBuild;

	private int packetSize;

	private BcdlOrderSentinel sentinel;

	private ExecutorService threadPool = Executors.newFixedThreadPool(10);

	@Resource(name = "bcdlConfig")
	private Map<String, String> bcdlConfig;

	@Override
	public void doTask() {
		logger.info("packetBuild_" + packetBuild + "银企直连付款job--开始，bank=" + bank);
		logger.error("param sys.id = " + bcdlConfig.get("sys.id"));
		logger.error("param batch.checkorder.retry.time = " + bcdlConfig.get("batch.checkorder.retry.time"));
		logger.error("batch.checkorder.successrate.threshold" + bcdlConfig.get("batch.checkorder.successrate.threshold"));
		retrySendBank(bank);
		process(bank);
		logger.info("packetBuild_" + packetBuild + "银企直连付款job--结束，bank=" + bank);
	}

	public void process(String bank) {
		if (sentinel.isFuse()) {
			logger.error("packetBuild_" + packetBuild + bank + ",暂停付款任务");
			return;
		}

		// modified by zyt,2017-10-10,抽出公用的合法时间校验到bankOrderManager中，时间校验前置，防止查询db后又被时间拦截，浪费db与服务的io
		if(!bankOrderManager.isLegalTime(bank)){
			return;
		}

		// 继续对账
		String beanName = getSendBankBeanName(bank);
		if (false == SpringContextUtil.containsBean(beanName)) {
			logger.info("packetBuild_" + packetBuild +  + remainder + "spring bean does not exist: " + beanName);
			return;
		}

		// try {
		StopWatch sw = new StopWatch();
		sw.start();
		Deque<String> bankOrders = getSendBankOrder(bank);
		Deque<String> orderIds = new LinkedList<String>();
		for (String bankOrderId : bankOrders) {
			BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class, bankOrderId);
			// 非生产环境、非一分钱交易直接置为“99”失败
			if (!"prod".equals(bcdlConfig.get("sys.id")) && !"0.01".equals(bankOrder.getSendBankAmt().toString())) {
				bankOrderManager.updateFail(bankOrder);
			} else {
				orderIds.add(bankOrder.getOrderId());
			}
		}
		Map<String, List<BankOrder>> ass = assSendBankOrder(orderIds);
		sw.split();
		logger.error("packetBuild_" + packetBuild + bank + "-----------getSendBankOrder耗时=" + sw.getSplitTime());
		logger.error("packetBuild_" + packetBuild + "-----------"+bank+"发往银行记录总数="+ass.size());

		BcdlOrderSendBankService sendBankService = (BcdlOrderSendBankService) SpringContextUtil.getBean(beanName);
		// 批量包发起
		for (String packetNo : ass.keySet()) {
			BcdlResult result = null;
			BcdlPacketRes res = new BcdlPacketRes();
			try {
				//List<BankOrder> bankOrderes = ass.get(packetNo);
				//for(BankOrder bankOrder: bankOrderes){
				//	logger.error("插入发往银行日志--开始,gopayOrderId="+ bankOrder.getOrderId() + ",packetNo="+packetNo+ ",bank=" + bank + ",packetBuild=" + packetBuild + remainder);
				//	bankOrderManager.saveBcdlSendBankLog(bankOrder);//插入发往银行日志 by lizheng 20170719
				//	logger.error("插入发往银行日志--结束,gopayOrderId="+ bankOrder.getOrderId() + ",packetNo="+packetNo+ ",bank=" + bank + ",packetBuild=" + packetBuild + remainder);
				//}
				
				logger.error("packetBuild_" + packetBuild + "银企直连 发送银行--开始 ，packetNo=" + packetNo + ",bank=" + bank);
				result = sendBankService.send4batch(ass.get(packetNo), packetNo, label, bank);
				logger.error("packetBuild_" + packetBuild + "银企直连 发送银行--结束 ，packetNo=" + packetNo + ",bank=" + bank + ",resultCode=" + result.getResultCode());

				if (ProcCodeConstants.PROC_CODE_100E6047.equals(result.getResultCode())) {
					logger.error("packetBuild_" + packetBuild + "银企直连 超时休眠--开始 ，packetNo=" + packetNo + ",bank=" + bank);
					Thread.sleep(5000);
					logger.error("packetBuild_" + packetBuild + "银企直连 超时休眠--结束 ，packetNo=" + packetNo + ",bank=" + bank);
				} else if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
					int retryTime = Integer.parseInt(bcdlConfig.get("batch.checkorder.retry.time"));
					for (int i = 0; i < retryTime; i++) {
						res = sendBankService.query4batch(packetNo, label, bank);
						if (!queryAgain(res, i)) {
							break;
						}
						Thread.sleep(3000);
					}
					if (ProcCodeConstants.PROC_CODE_100S1000.equals(res.getResultCode())) {
						for (BcdlResult bcdlResult : res.getBcdlResults()) {
							BcdlResultDeal4BatchThread dealThread = new BcdlResultDeal4BatchThread(bcdlResult,gassPayService);
							threadPool.execute(dealThread);
						}
					}

				}
				int threadSize = ((ThreadPoolExecutor) threadPool).getActiveCount();

				if (threadSize > 200) {
					logger.error("packetBuild_" + packetBuild + ",bank=" + bank + ",发送银行线程数超过200");
				}
			} catch (Exception e) {
				logger.error("packetBuild_" + packetBuild + "发送银行异常 ，packetNo=" + packetNo + ",bank=" + bank, e);
			} finally {
				sentinel.batchPatrol(packetNo, result, res);
				if (sentinel.isFuse()) {
					logger.error("packetBuild_" + packetBuild + bank + ",暂停付款任务");
					break;
				}
			}

		}

		// 批量包对账
		// for (String packetNo : ass.keySet()) {
		// BcdlPacketRes res = sendBankService.query4batch(packetNo, label,
		// bank);
		// for(BcdlResult bcdlResult:res.getBcdlResults()){
		// BcdlResultDeal4BatchThread dealThread = new
		// BcdlResultDeal4BatchThread(bcdlResult,bcdlConfig.get("gass.notify.url"));
		// threadPool.execute(dealThread);
		// }
		// }
		// } catch (Exception e) {
		// logger.error("packetBuild_" + packetBuild+"checkOrder error message: ,bank="+bank,
		// e);
		// }
	}

	public List<Object[]> getCheckBcdlOrderByBank(String bank, String orderStatus, int modInt, int remainder, String across, int pageIndex, int pageSize) {
		StringBuffer sql = new StringBuffer(250);
		sql.append("select b.GOPAY_OUT_ORDER_ID,b.GOPAY_ORDER_ID from BIS_BANK_MAIN_ORDER b ");
		if (StringUtils.isNotBlank(across) || "ICBC".equals(bank)) {
			sql.append(" left join BIS_BANK_BCDL_ORDER o on o.gopay_out_order_id = b.gopay_out_order_id ");
		}
		sql.append(" where b.ORDER_STATUS = :orderStatus ");
		if (modInt != 1) {
			sql.append(" and mod(b.GOPAY_ORDER_ID,:modInt)=:remainder ");
		}
		// if(modInt==2&&remainder==0){
		// logger.error("packetBuild_" + packetBuild+"_mod_"+modInt+"_remainder_"+remainder);
		// sql.append(" and substr(b.GOPAY_ORDER_ID,-1) in ('0','2','4','6','8') ");
		// }else if(modInt==2&&remainder==1){
		// logger.error("packetBuild_" + packetBuild+"_mod_"+modInt+"_remainder_"+remainder);
		// sql.append(" and substr(b.GOPAY_ORDER_ID,-1) in ('1','3','5','7','9') ");
		// }
		sql.append(" and b.BANK_BIZ_PROD_CODE = :bankBizProdCode ");
		sql.append(" and b.ORDER_TYPE = :orderType ");
		sql.append(" and b.GOPAY_BANK_CODE = :bankCode ");
		if (StringUtils.isNotBlank(across)) {
			if(across.equals("0")){
				sql.append(" and o.IS_CROSSBANK = 0 ");
			}else{
				sql.append(" and o.IS_CROSSBANK in (1,2) ");
			}
		}
		if ("ICBC".equals(bank)) {
			// 是否重发 1 是 0 否
			sql.append(" and o.IS_REONLINEPAY = :reonlinepay ");
		}
		sql.append(" and b.TOTAL_CHECK_TIMES <= :totalCheckTimes ");
		sql.append(" and b.SEND_BANK_TM >=to_date(:beginTime ,'yyyyMMddHH24miss') ");
		// 修改T+1插队到T+0问题，改成订单号降序
		sql.append(" order by b.TOTAL_CHECK_TIMES, b.GOPAY_ORDER_ID desc ");

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderStatus", orderStatus);
		params.put("bankBizProdCode", BisBankBusinessProd._09.value);
		params.put("orderType", BankOrderType.GOPAY_BIS_ORDER);
		params.put("bankCode", bank);
		params.put("totalCheckTimes", 7);
		if (modInt != 1) {
			params.put("modInt", modInt);
			params.put("remainder", remainder);
		}
		/*if (StringUtils.isNotBlank(across)) {
				params.put("across", "0");
			
		}*/
		if ("ICBC".equals(bank)) {
			params.put("reonlinepay", 0);// 是否重发 1 是 0 否
		}
		params.put("beginTime", recentlyTime());
		List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), params, pageIndex, pageSize);
		return list;
	}

	private Boolean queryAgain(BcdlPacketRes res, int num) {
		if (res.isSuccess() && res.getBcdlResults() != null && res.getBcdlResults().size() > 0) {
			int successNum = 0;
			for (BcdlResult result : res.getBcdlResults()) {
				if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
					successNum++;
				}
			}
			logger.error("批次号" + res.getPacketNo() + "第" + (num + 1) + "次对单，size=" + res.getBcdlResults().size() + ", successNum=" + successNum);
			double accuracy_num = successNum * 100 / res.getBcdlResults().size();
			if (accuracy_num >= 50) {
				return false;
			}
		}
		return true;
	}

	private String recentlyTime() {
		Calendar calendar = Calendar.getInstance();

		// 开始时间--最近1天
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -2);
		String beginTime = DateUtils.format(calendar.getTime(), "yyyyMMddHHmmss");

		return beginTime;
	}

	// private String buildBCDLTimeClause(){
	// Calendar calendar = Calendar.getInstance();
	//
	// //开始时间--最近1天
	// calendar.setTime(new Date());
	// calendar.add(Calendar.DAY_OF_MONTH, -1);
	// String beginTime=DateUtils.format(calendar.getTime(), "yyyyMMddHHmmss");
	//
	// StringBuilder sb=new
	// StringBuilder(" and b.SEND_BANK_TM >to_date('"+beginTime+"','yyyyMMddHH24miss') ");
	//
	// return sb.toString();
	// }
	public Deque<String> getSendBankOrder(String bank) {
		List<Object[]> list = getCheckBcdlOrderByBank(bank, BankOrderStatus.ACCEPTED, modInt, remainder, across, 1, MAX_SIZE);
		Deque<String> orderIds = new LinkedList<String>();

		for (Object[] bankOrderId : list) {
			logger.error("packetBuild_" + packetBuild + "_mod_" + modInt + "_remainder_" + remainder + "orderId:" + bankOrderId[0]);
			orderIds.add(StringTools.checkNulltoString(bankOrderId[0]));
		}
		return orderIds;
	}

	public Map<String, List<BankOrder>> assSendBankOrder(Deque<String> bankOrders) {
		Map<String, List<BankOrder>> ass = new HashMap<String, List<BankOrder>>();
		//修改包号生成规则
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
		String date = df.format(new Date());
	    String batchNo = date+packetBuild;
		int loop = bankOrders.size() / packetSize + ((bankOrders.size() % packetSize == 0) ? 0 : 1);
		for (int i = 0; i < loop; i++) {
			List<BankOrder> chip = new ArrayList<BankOrder>();
			for (int j = 0; j < packetSize; j++) {
				if (bankOrders.size() <= 0)
					break;
				BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class, bankOrders.pop());
				/*
				 * if (!isLargeCrossWorkTime(new Date())) { if
				 * (SettlementExchangeConstants
				 * .STLM_EX_ICBC_CROSS.equals(getStlmEx
				 * (bankOrder.getOrderId()))) {
				 * logger.error(bankOrder.getOrderId() +
				 * " BcdlOrderBatchSendAIOTaskImpl assSendBankOrder not isLargeCrossWorkTime"
				 * ); continue; } }
				 */
				chip.add(bankOrder);
			}
			if (chip != null && chip.size() > 0) {
				ass.put(batchNo + DateUtils.getCurrDate("ssSSS") + RandomStringUtils.randomNumeric(11), chip);
			}
		}
		return ass;
	}
	
	// 重发
	private void retrySendBank(String bankCode) {
		if (sentinel.isFuse()) {
			logger.error("retrySendBank," + bank + ",暂停付款任务");
			return;
		}

		// modified by zyt,2017-10-10,抽出公用的合法时间校验到bankOrderManager中，时间校验前置，防止查询db后又被时间拦截，浪费db与服务的io
		if(!bankOrderManager.isLegalTime(bank)){
			return;
		}

		String beanName = getSendBankBeanName(bank);
		if (false == SpringContextUtil.containsBean(beanName)) {
			logger.info("retrySendBank, spring bean does not exist: " + beanName);
			return;
		}

		StopWatch sw = new StopWatch();
		sw.start();
		List<String> sendOrders = getRetrySendBankOrder(bankCode);
		sw.split();
		logger.error("retrySendBank," + bank + "-----------getSendBankOrder耗时=" + sw.getSplitTime());
		logger.error("retrySendBank," + bank + "发往银行记录总数=" + sendOrders.size());

		try {
			// 继续对账
			BcdlOrderSendBankService sendBankService = (BcdlOrderSendBankService) SpringContextUtil.getBean(beanName);
			HttpTransport notifyGass = new HttpTransport();
			notifyGass.setSendEncoding("UTF-8");
			for (String bankOrderId : sendOrders) {
				BcdlResult result = null;
				BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class, bankOrderId);
				try {
					// 非生产环境、非一分钱交易直接置为“99”失败
					if (!"prod".equals(bcdlConfig.get("sys.id")) && !"0.01".equals(bankOrder.getSendBankAmt().toString())) {
						bankOrderManager.updateFail(bankOrder);
					} else {
						//logger.error("插入发往银行日志--开始,gopayOrderId="+bankOrder.getOrderId() + ",bank=" + bank + ",packetBuild=" + packetBuild);
						//bankOrderManager.saveBcdlSendBankLog(bankOrder);//插入发往银行日志 by lizheng 20170719
						//logger.error("插入发往银行日志--结束,gopayOrderId="+bankOrder.getOrderId() + ",bank=" + bank + ",packetBuild=" + packetBuild);
						logger.error("retrySendBank,银企直连 发送银行--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank + ",packetBuild=" + packetBuild);
						if (!isLargeCrossWorkTime(new Date())) {
							// 工行跨行大额订单增加发送时间限制
							if (SettlementExchangeConstants.STLM_EX_ICBC_CROSS.equals(getStlmEx(bankOrder.getOrderId()))) {
								logger.error(bankOrder.getOrderId() + " BcdlOrderBatchSendAIOTaskImpl retrySendBank not isLargeCrossWorkTime");
								continue;
							}
						}
						result = sendBankService.sendBank(bankOrder, label);
						logger.error("retrySendBank,银企直连 发送银行--结束 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank + ",packetBuild=" + packetBuild + ",resultCode="
								+ result.getResultCode());

						Map<String, String> param = new HashMap<String, String>();
						if (ProcCodeConstants.PROC_CODE_100E6027.equals(result.getResultCode())) {
							param.put("resultCode", "2");
							param.put("resultMsg", result.getErrorMsg());
							//add by zyt,2017-10-13 ,是否需要做失败的拒绝账务，
							if(result.isNeedRefund()){
								logger.info("发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
								param.put("needRefund", "1");
							}
						} else if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode())) {
							param.put("resultCode", "1");
						} else if (ProcCodeConstants.PROC_CODE_100E6047.equals(result.getResultCode())) {
							logger.error("retrySendBank,银企直连 超时休眠--开始 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
							Thread.sleep(5000);
							logger.error("retrySendBank,银企直连 超时休眠--结束 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank);
							continue;
						} else {
							param.put("resultCode", "3");
						}
						param.put("remark", "1");
						param.put("gopayOrderId", bankOrder.getOrderId());
						/*notifyGass.setUrl(bankOrder.getRemark2());
						notifyGass.submit(param);*/ // 生产优化10期 lx httpclient 替换为 hessian
						gassPayService.bcdlNotifyGass(param);
					}
				} catch (Exception e) {
					logger.error("retrySendBank,发送银行异常 ，orderId=" + bankOrder.getOrderId() + ",bank=" + bank, e);
				} finally {
					sentinel.patrol(bankOrder, result);
					if (sentinel.isFuse()) {
						logger.error("retrySendBank," + bank + ",暂停付款任务");
						break;
					}
				}
			}
		} catch (Exception e) {
			logger.error("retrySendBank, checkOrder error message: ,bank=" + bank, e);
		}
	}

	private List<String> getRetrySendBankOrder(String bankCode) {
		// TODO Auto-generated method stub
		List<Object[]> list = getRetrySendBankOrderByBank(bank, BankOrderStatus.ACCEPTED, modInt, remainder, across, 1, MAX_SIZE);
		List<String> orderIds = new ArrayList<String>();
		for (Object[] bankOrderId : list) {
			logger.error("RetrySendBank, packetBuild_" + packetBuild + "_mod_" + modInt + "_remainder_" + remainder + "orderId:" + bankOrderId[0]);
			orderIds.add(StringTools.checkNulltoString(bankOrderId[0]));
		}
		return orderIds;
	}

	public List<Object[]> getRetrySendBankOrderByBank(String bank, String orderStatus, int modInt, int remainder, String across, int pageIndex, int pageSize) {

		StringBuffer sql = new StringBuffer(250);
		sql.append("select b.GOPAY_OUT_ORDER_ID,b.GOPAY_ORDER_ID from BIS_BANK_MAIN_ORDER b ");
		if (StringUtils.isNotBlank(across) || "ICBC".equals(bank)) {
			sql.append(" left join BIS_BANK_BCDL_ORDER o on o.gopay_out_order_id = b.gopay_out_order_id ");
		}
		sql.append(" where b.ORDER_STATUS = :orderStatus ");
		if (modInt != 1) {
			sql.append(" and mod(b.GOPAY_ORDER_ID,:modInt)=:remainder ");
		}
		sql.append(" and b.BANK_BIZ_PROD_CODE = :bankBizProdCode ");
		sql.append(" and b.ORDER_TYPE = :orderType ");
		sql.append(" and b.GOPAY_BANK_CODE = :bankCode ");
		if (StringUtils.isNotBlank(across)) {
			sql.append(" and o.IS_CROSSBANK = :across ");
		}
		sql.append(" and b.TOTAL_CHECK_TIMES <= :totalCheckTimes ");
		sql.append(" and b.SEND_BANK_TM >=to_date(:beginTime ,'yyyyMMddHH24miss') ");
		if ("ICBC".equals(bank)) {
			// 是否重发 1 是 0 否
			sql.append(" and o.IS_REONLINEPAY = :reonlinepay ");
		}

		// 修改T+1插队到T+0问题，改成订单号降序
		sql.append(" order by b.TOTAL_CHECK_TIMES, b.GOPAY_ORDER_ID desc ");

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderStatus", orderStatus);
		params.put("bankBizProdCode", BisBankBusinessProd._09.value);
		params.put("orderType", BankOrderType.GOPAY_BIS_ORDER);
		params.put("bankCode", bank);
		params.put("totalCheckTimes", 7);
		if (modInt != 1) {
			params.put("modInt", modInt);
			params.put("remainder", remainder);
		}
		if (StringUtils.isNotBlank(across)) {
			params.put("across", across);
		}
		if ("ICBC".equals(bank)) {
			params.put("reonlinepay", 1);// 是否重发 1 是 0 否
		}
		params.put("beginTime", recentlyTime());
		List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), params, pageIndex, pageSize);
		return list;
	}

	private String getStlmEx(String gopayOrderId) {
		StringBuffer sql = new StringBuffer(250);
		Map<String, Object> map = new HashMap<String, Object>();
		sql.append(" SELECT ").append(" STLM_EX, GOPAY_ORDER_ID ").append(" FROM CPS_GEN_PAY_ORDER cp ").append(" WHERE 1=1 ").append(" AND cp.GOPAY_ORDER_ID =:gopayOrderId");
		map.put("gopayOrderId", gopayOrderId);
		List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), map);
		if (list != null && list.size() > 0) {
			return StringTools.checkNulltoString(list.get(0)[0]);
		}
		return null;
	}

	private boolean isLargeCrossWorkTime(Date date) {
		int hour = date.getHours();
		int minute = date.getMinutes();
		if (hour < 9 || hour > 16 || (hour == 16 && minute > 50) || (hour == 9 && minute < 10)) {
			logger.info("BcdlOrderBatchSendAIOTaskImpl isLargeCrossWorkTime false");
			return false;
		}
		return true;
	}

	// BankOrder bankOrder = bisBankOrderQueryDAO.find(BankOrder.class,
	// bankOrderId);
	// 11/5+((11%5==0)?0:1)
	private String genPacketNo(String bankCode) throws GopayException {
		String beanName = bankCode + "-BCDL";
		return beanName;
	}

	private String getSendBankBeanName(String bankCode) {
		String beanName = bankCode + "-BCDL";
		return beanName;
	}

	public BankOrderService getBankOrderService() {
		return bankOrderService;
	}

	public void setBankOrderService(BankOrderService bankOrderService) {
		this.bankOrderService = bankOrderService;
	}

	public void setBank(String bank) {
		this.bank = bank;
	}

	public CpsGeneralMainOrderQueryManager getMainOrderQuery() {
		return mainOrderQuery;
	}

	public void setMainOrderQuery(CpsGeneralMainOrderQueryManager mainOrderQuery) {
		this.mainOrderQuery = mainOrderQuery;
	}

	public BankOrderManager getBankOrderManager() {
		return bankOrderManager;
	}

	public void setBankOrderManager(BankOrderManager bankOrderManager) {
		this.bankOrderManager = bankOrderManager;
	}

	public void setRemainder(int remainder) {
		this.remainder = remainder;
	}

	public void setModInt(int modInt) {
		this.modInt = modInt;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public void setAcross(String across) {
		this.across = across;
	}

	public void setSentinel(BcdlOrderSentinel sentinel) {
		this.sentinel = sentinel;
	}

	public void setPacketSize(int packetSize) {
		this.packetSize = packetSize;
	}

	public void setPacketBuild(String packetBuild) {
		this.packetBuild = packetBuild;
	}

}
